﻿using System.Threading;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace GameFramework.ObjectPool
{
    public static class ObjectPoolCoreExtensions
    {
        /// <summary>
        /// 提供可取消的方式异步实例化指定GameObject 若token被取消 则会回收实例化成功的资源 并返回null
        /// </summary>
        public static async UniTask<GameObject> InstantiateAsyncWithCancellationToken(this IObjectPoolCore core, string assetKey, CancellationToken token)
        {
            if (token.IsCancellationRequested)
                return null;

            var gameObject = await core.InstantiateAsync(assetKey);
            if (gameObject == null)
                return null;

            if (!token.IsCancellationRequested)
                return gameObject;
            
            core.Release(gameObject);
            return null;
        }
    }
}